#pragma once
#include <cstdio>
#include <cstdarg>
#include <string>
#include <ctime>
#include <unistd.h>

// 简单日志
// 等级由低到高：debug < info < warn < Error < Fatal

enum LogLevel// 日志级别
{
    DEBUG = 0,
    INFO,
    WARNING,
    ERROR,
    FATAL,
    UNKNOW
};

static std::string getlevel(int loglevel)
{
    switch (loglevel)
    {
    case DEBUG:
        return "DEBUG";
    case INFO:
        return "INFO";
    case WARNING:
        return "WARNING";
    case ERROR:
        return "ERROR";
    case FATAL:
        return "FATAL";
    default:
        return "UNKNOW";
    }
}

static std::string gettime()
{
    time_t currenttime = time(nullptr);
    struct tm *formattime = localtime(&currenttime);
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "%d-%d-%d %d:%d:%d",
             formattime->tm_year + 1900, formattime->tm_mon + 1, formattime->tm_mday,
             formattime->tm_hour, formattime->tm_min, formattime->tm_sec);
    return buffer;
}

// 日志格式：日志等级 时间 pid 消息体
void logmessage(int loglevel, const char *format, ...)
{
    char logleft[1024];
    snprintf(logleft, sizeof(logleft), "[%s] [%s] [%d] ", getlevel(loglevel).c_str(), gettime().c_str(), getpid());

    char logright[1024];
    va_list ap;
    va_start(ap, format);
    vsnprintf(logright, sizeof(logright), format, ap);
    va_end(ap);

    printf("%s%s\n", logleft, logright);
}
